﻿/************************************************************************
* Copyright (c) 2018 All Rights Reserved.
*命名空间：AOP.Filter.Result
*文件名： ResultFilterAttribute
*创建人： kingling
*创建时间：2018/7/5 11:09:57
*描述
*=======================================================================
*修改标记
*修改时间：2018/7/5 11:09:57
*修改人：kingling
*描述：
************************************************************************/

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace AOP.Filter.Result
{
    /// <summary>
    /// 结果过滤器
    /// </summary>
    public class AopResultFilterAttribute : IResultFilter
    {
        public void OnResultExecuted(ResultExecutedContext context)
        {
            //throw new NotImplementedException();
        }
        /// <summary>
        /// 结果过滤
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuting(ResultExecutingContext context)
        {
            var actiondescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            if (actiondescriptor.MethodInfo.ReturnType.Name == "IActionResult")
            {
                return;
            }
            //控制器上是否有过滤标签
            var with_out_controller = context.Controller.GetType().IsDefined(typeof(NativeAttribute), true);
            if (with_out_controller)
            {
                return;
            }
            //控制器上是否有过滤标签
            var with_out_action = actiondescriptor.MethodInfo.IsDefined(typeof(NativeAttribute), true);
            if (with_out_action)
            {
                return;
            }
            //重新组建result
            var result = context.Result as ObjectResult;
            var msg = new Msg
            {
                code = 0,
                data = result == null ? null : result.Value
            };
            context.Result = new JsonResult(msg);
        }
    }
}
